from typing import Dict, Any, List
import os
from .base_formatter import BaseFormatter

class TextFormatter(BaseFormatter):
    """文本报告格式化器"""
    
    def __init__(self, output_dir: str):
        super().__init__(output_dir)
        self.colors = {
            'HEADER': '\033[95m',
            'BLUE': '\033[94m',
            'GREEN': '\033[92m',
            'YELLOW': '\033[93m',
            'RED': '\033[91m',
            'ENDC': '\033[0m',
            'BOLD': '\033[1m',
            'UNDERLINE': '\033[4m'
        }
    
    def format_report(self, results: List[Dict[str, Any]], scan_info: Dict[str, Any]) -> None:
        """生成文本格式的报告
        
        Args:
            results: 扫描结果列表
            scan_info: 扫描信息字典
        """
        filename = os.path.join(self.output_dir, 'scan_report.txt')
        content = []
        
        # 添加标题
        content.append(self._colored("端口扫描报告", 'HEADER'))
        content.append(self._colored("=" * 50, 'HEADER'))
        content.append("")
        
        # 添加扫描信息
        content.append(self._colored("扫描开始时间: ", 'BLUE') + self._format_timestamp(scan_info['start_time']))
        content.append(self._colored("扫描结束时间: ", 'BLUE') + self._format_timestamp(scan_info['end_time']))
        content.append(self._colored("扫描主机数: ", 'BLUE') + str(scan_info['total_hosts']))
        content.append(self._colored("扫描端口数: ", 'BLUE') + str(scan_info['total_ports']))
        content.append("")
        
        # 添加扫描结果
        current_target = None
        for result in sorted(results, key=lambda x: (x['target'], x['port'])):
            if current_target != result['target']:
                current_target = result['target']
                content.append("")
                content.append(f"{self._colored('目标主机: ', 'BOLD')}{self._colored(current_target, 'UNDERLINE')}")
                content.append(self._colored("-" * 30, 'BLUE'))
            
            # 获取状态样式
            status_map = {
                'open': ('开放', 'GREEN'),
                'closed': ('关闭', 'RED'),
                'filtered': ('被过滤', 'YELLOW')
            }
            status_text, status_color = status_map.get(result['status'], (result['status'], 'BLUE'))
            
            # 基本端口信息
            service = result['service'] if result['service'] else "未知"
            latency = f"{result['latency']}ms" if result['latency'] else "N/A"
            
            port_info = f"端口 {result['port']}: {self._colored(status_text, status_color)} "
            port_info += f"({self._colored(service, 'BLUE')}) - "
            port_info += f"响应时间: {latency}"
            content.append(port_info)
            
            # 服务详细信息
            if result['service_info'] and result['status'] == 'open':
                service_details = self._get_service_details(result['service_info'])
                for detail in service_details:
                    content.append(f"  {self._colored(detail, 'BLUE')}")
        
        # 写入文件
        self._write_file(filename, '\n'.join(content))
    
    def _colored(self, text: str, color: str) -> str:
        """为文本添加颜色
        
        Args:
            text: 要着色的文本
            color: 颜色代码
            
        Returns:
            str: 着色后的文本
        """
        return f"{self.colors.get(color, '')}{text}{self.colors['ENDC']}" 